<template>
  <div style="border: 1px solid #ccc;">
      <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editor"
          :defaultConfig="toolbarConfig"
          :mode="mode"
      />
      <Editor
          style="height: 500px; overflow-y: hidden;"
          v-model="html"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="onCreated"
          @onChange="onChange"
      />
  </div>
</template>
<script>
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
  import { getToken } from '@/utils/auth';
  import { uploadFileToBucket } from '@/utils/uploadVideoCos';

  export default {
    components: { Editor, Toolbar },
    props: {
      content: ""
    },
    data() {
      return {
        editor: null,
        html: '',
        toolbarConfig: {
          excludeKeys: ["fullScreen", "group-video"]
        },
        editorConfig: { 
          placeholder: '请输入内容...',
          MENU_CONF: {
            //   配置上传图片
            uploadImage: {
              server: process.env.VUE_APP_BASE_API+"/system/file/upload/"+Math.floor(Math.random() * 10),//后端给的文件上传接口
              fieldName: "file",
              // meta: {},//后端接口要求携带的参数
              // // 请求头
              headers: { authorization: 'Bearer ' + getToken() },
              // timeout: 5 * 1000, // 5s 超时时间
              // //选择文件时的类型限制，默认为['image/*'] 如不想限制，则设置为 []
              allowedFileTypes: ['image/*'],
              maxFileSize: 30 * 1024 * 1024, //1g //设置大点 不然图片过大会报错
              base64LimitSize: 0, // 1g 以下插入 base64
              autoCrop: false,
              // 自定义插入图片
              customInsert: async (res, insertFn) => {
                console.log(222,res);
                
                // insertFn(res.data.url);
                const { fileName, url } = res.data;
                // 给图片加上默认宽度
                const imageNode = {
                  type: "image",
                  src: url,
                  href: url,
                  alt: fileName,
                  width: "",
                  height: "",
                  style: {
                    width: "100%",
                  },
                  // 其他属性 ...
                  children: [{ text: "" }], // void 元素必须有一个 children ，其中只有一个空字符串，重要！！！
                };
                this.editor.insertNode(imageNode);
              },
            },
            uploadVideo: {
              server:"",
              fieldName: "file",
              meta: {},
              // 请求头
              headers: { token: localStorage.getItem("token")},
              timeout: 5 * 1000, // 5s 超时时间
              //选择文件时的类型限制，默认为['video/*'] 如不想限制，则设置为 []
              allowedFileTypes: ["video/*"],
              async customUpload (file,insertFn) {
                uploadFileToBucket(file, (url) => {
                  insertFn(url);
                })
              },
            },
          }, 
        },
        mode: 'default', // or 'simple'
      }
    },
    methods: {
      imgTagAddStyle(htmlstr){
        const newHtml = htmlstr.replace(/(<img[^>]*style=")(.*?)("[^>]*>)/g, (match, p1, p2, p3) => {
          return p1 + 'width:100%;' + p3;
        });
        return newHtml;
      },
      onCreated(editor) {
        this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      },
      onChange(editor) {
        this.html = this.imgTagAddStyle(this.html);
        this.$emit("changeData", this.html, editor.getText());
      },
      handleClear () {
        this.editor.txt.clear()
      }
    },
    created () {
      this.html = this.content;
    },
    watch: {
      content(newValue,oldValue) {
        this.html = newValue;
      }
    },
    mounted() {
      // 模拟 ajax 请求，异步渲染编辑器
      setTimeout(() => {
        // this.html = '<p>模拟 Ajax 异步设置内容 HTML</p>'
      }, 1500)
    },
    // beforeDestroy() {
    //   const editor = this.editor
    //   if (editor == null) return
    //   editor.destroy() // 组件销毁时，及时销毁编辑器
    //   this.html = ''
    //   editor.txt.clear()
    // },
  }
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>